import hashlib
import os
import sys
import time
from datetime import datetime
from lib.crc16 import crc16Bytes

class my_sign():

    def __init__(self, path):
        pass

    def get_data(self, path):
        data = []
        if (path.find(".dfu") > -1) | (path.find(".bin") > -1):
            with open(path, 'rb') as f:
                data = f.read()
                f.close()
        return data

    def hex_output(self, bytes_s):
        i = 0
        s = ""
        for data in bytes_s:
            if(i >= 16):
                i = 0
                s = s[:-1] + "\n"
            i = i + 1
            s = s + '0x' + ('%02X' % data) + ", "
        return s[:-2]

    def buff_output(self, input_s, buf_head):
        input_s = input_s.replace("\n", "\n    ")
        input_s = "    " + input_s
        input_s = "const static unsigned char " + \
            buf_head + "[] = {\n" + input_s + "};"

        return input_s

    def get_out_path(self, src_path, out_path):
        if out_path is not None:
            file_path = out_path
            # print("file_path", file_path)
            if((file_path.endswith('\\') is not True) and file_path.find('\\') > 0):
                file_path = file_path + '\\'
            if((file_path.endswith('/') is not True) and file_path.find('/') > 0):
                file_path = file_path + '/'
            filename = file_path + os.path.split(src_path)[1]
        else:
            filename = src_path
        print(filename)
        if filename.find(".dfu")>-1:
            filename = filename.replace(".dfu", ".bin")
        elif filename.find(".bin")>-1:
            filename = filename.replace(".bin", ".dfu")
        return filename

    def get_crc16(self, f_data):
        crc16 = crc16Bytes(f_data, False)
        return crc16

    def get_head_info(self, crc16_val, file_size):
        hrad_info = []
        xjq = "{}||{}||".format(crc16_val.hex() ,str(file_size))
        # print(xjq)

        hrad_info = xjq.encode()
        # print(hrad_info)
        return hrad_info
